unit FlatSingle;

interface

{$I FlatStyle.inc}

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;

type
  TFlatSingle = class(TComponent)
  private
    { Private declarations }
    FActive: boolean;
    hmutex: Thandle;
    FTitle: string;
    procedure SetActive(Value: boolean);
  protected
    { Protected declarations }
    procedure Loaded; override;
    procedure RunSingle(Single:Boolean);
  public
    { Public declarations }
    constructor Create(AOwner: TComponent); override;
  published
    { Published declarations }
    property Active: boolean read FActive write SetActive default True;
    property Title: string read FTitle write FTitle;
  end;

implementation

constructor TFlatSingle.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FActive := True;
  FTitle  := 'The program already run!';
end;

procedure TFlatSingle.Loaded;
begin
  inherited Loaded;
  RunSingle(Active);
end;

procedure TFlatSingle.RunSingle(Single: Boolean);
begin
  if (Single)and(not(csDesigning in ComponentState)) then
  begin
   with Application do
   begin
    try
      hmutex := OpenMutex(MUTEX_ALL_ACCESS, False, pchar(Title));
      if hmutex = 0 then
      begin
        inherited;
        hmutex := CreateMutex(nil, False, pchar(Title));
        ReleaseMutex(hmutex);
      end
      else
      begin
        ShowMainForm := False;
        ShowMessage(FTitle);
        Terminate;
      end;
    finally
    end;
   end;
  end;
end;

procedure TFlatSingle.SetActive(Value: boolean);
begin
  FActive := Value;
  RunSingle(FActive);
end;

end.

